﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using Android.App;
using System.Diagnostics;
using Android.Runtime;
using System.Text.RegularExpressions;
using Android.Graphics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using AndroidApp;
using Android.Content;

namespace ComApp
{
    public partial class HttpService
    {
        //public void DownloadImage(string postUrl, string postCode, int size, Action<Bitmap> action)
        //{
        //    var md5 = this.GetMd5(postUrl + postCode);
        //    var localFileName = System.IO.Path.Combine(this.CachePath, md5 + ".jpg");
        //    if (System.IO.File.Exists(localFileName))
        //    {
        //        var bitmap = this.GetBitmap(localFileName, size);
        //    }
        //    else
        //    {

        //            var imgUrl = @"http://bs.baidu.com/imemmi-tiny/%2F20140220220426_bouD45ME8a.jpg?sign=MBOT-iwImKL1Q98ibe5rybNr9CGRah0aZXyM-n57ZdYJNmDeVwQ5S1AHZh0jTMxs%3D&time=1392907180";
        //            webClient.DownloadFileCompleted += (o, e) =>
        //                {
        //                    if (e.Error != null || e.Cancelled)
        //                    {
        //                        if (File.Exists(localFileName))
        //                            File.Delete(localFileName);
        //                    }
        //                    else
        //                    {
        //                        var bitmap = this.GetBitmap(localFileName, size);
        //                        if (bitmap != null)
        //                            action(bitmap);
        //                    }
        //                };
        //            webClient.DownloadFileAsync(new Uri(imgUrl), localFileName);
        //        }
        //    }
        //}


        /// <summary>
        /// 直接下载显示图片,不缓存，直接返回bitmap，不在本地保存物理文件
        /// </summary>
        /// <param name="imageView"></param>
        /// <param name="httpImageUrl"></param>
        /// <param name="sampleSize"></param>
        public void DownloadImageByHttp(string httpImageUrl, int sampleSize, Action<Bitmap> action)
        {
            using (var webClient = new WebClient())
            {
                webClient.DownloadDataCompleted += (o, e) =>
                {
                    if (e.Result != null)
                    {
                        var bitmap = BitmapFactory.DecodeStream(new MemoryStream(e.Result), null, new BitmapFactory.Options() { InSampleSize = sampleSize, });
                        action(bitmap);
                    }
                };
                webClient.DownloadDataAsync(new Uri(httpImageUrl));
            }
        }

        /// <summary>
        /// 生成位图对象
        /// </summary>
        /// <param name="localUrl"></param>
        /// <returns></returns>
        public Bitmap GetBitmap(string localUrl, int sampleSize)
        {
            using (var stream = File.Open(localUrl, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
            {
                if (stream.Length > 0)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        stream.CopyTo(memoryStream);
                        stream.Close();
                        memoryStream.Position = 0;
                        var bitmap = BitmapFactory.DecodeStream(memoryStream, null, new BitmapFactory.Options() { InSampleSize = sampleSize });
                        stream.Dispose();
                        return bitmap;
                    }
                }
                return null;
            }
        }

        partial void SetAppDataPath()
        {
            this.AppDataPath = AppPath.Instance.AppDataPath;
        }

        public string DownloadPath
        {
            get
            {
                var dir = System.IO.Path.Combine(this.AppDataPath, "Download");
                if (!System.IO.Directory.Exists(dir))
                    System.IO.Directory.CreateDirectory(dir);

                return dir;
            }
        }


        public string GetLocalIpAddress()
        {
            try
            {
                var list = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
                foreach (var intf in list)
                {
                    var ipAddress = intf.GetIPProperties();
                    if (ipAddress.UnicastAddresses != null && ipAddress.UnicastAddresses.Count > 0)
                    {
                        return ipAddress.UnicastAddresses[0].Address.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                //AppUnity.Instance.LogService.Log(ex);
                AppUnity.Instance.LogService.Log(string.Format("获取IP失败{0}",ex.GetType().Name));
                return string.Empty;
            }
            return string.Empty;
        }
    }
}
